import axios from 'axios'
import router from '@/router/index'
import { delCookie, getCookie } from "@/utils/cookieUtils";
import { Notification } from 'element-ui'
// 创建axios实例
const service = axios.create({
  baseURL: '', // api 的 base_url
  timeout: 20000 // 请求超时时间 10秒
})

service.defaults.headers.common['Kebol_Token'] = getCookie("token")

// request拦截器
service.interceptors.request.use(
  config => {
    // store.dispatch('setLoading', true);
    if (getCookie("token") != undefined) {
      config.headers.Kebol_Token = getCookie("token") // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)


// response 拦截器
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    switch (error.response.status) {
      case 401:
        Notification.info({
          title: "温馨提示：",
          message: '登录已过期，请重新登录！',
          offset: 50
        });
        delCookie("token")
        break
      case 404:
        router.push('/404')
        break;
      default: {
        router.push('/500')
      }
    }

    return Promise.reject(error)
  }
)

export default service
